/**
 * 
 */
package bingo.monitor.datasource;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


/**
 * {@link ConnectionWapper}监控器，监控 {@link ConnectionWapper}的打开与关闭，检查是否存在连接泄露的情况
 * @author elvis
 */
public class ConnectionMonitor {
	
	private Map<ConnectionInfo, Boolean> connections = new ConcurrentHashMap<ConnectionInfo, Boolean>();
	
	private static ConnectionMonitor monitor = new ConnectionMonitor();
	
	public static ConnectionMonitor getMonitor(){
		return monitor;
	}
	
	public Set<ConnectionInfo> getConnectionInfos(){
		return connections.keySet();
	}
	
	/**
	 * 连接被获取后调用
	 */
	public void onConnectionOpen(DelegatingConnection connection){
		// create ConnectionInfo
		long openTime = System.currentTimeMillis();
		
		ConnectionInfo info = new ConnectionInfo();
		info.setOpenThread(Thread.currentThread().getName());
		info.setOpenTime(openTime);
		info.setOpenStack(Thread.currentThread().getStackTrace());
		info.setDataSource(connection.getDatasource().getName());
		
		// store it into map
		connection.setMonitorInfo(info);
		connections.put(info, Boolean.TRUE);
	}
	
	/**
	 * 连接被关闭后调用
	 */
	public void onConnectionClose(DelegatingConnection connection){
		ConnectionInfo info = connection.getMonitorInfo();
		
		if(null != info){
			info.setClosed(true);
			connections.remove(info);
		} else {
			System.err.println("connection info is null");
		}
	}
	
	public void removeConnectionInfo(ConnectionInfo connectionInfo){
		connections.remove(connectionInfo);
	}
}
